<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>张宸煜时间银行</title>
    <script src="https://cdn.tailwindcss.com"></script>
	<link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link href="./css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#8B5CF6',
                        neutral: '#1F2937',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
         /* 弹窗背景（遮罩层）：全屏半透明，防止点击底层内容 */
        .modal-overlay {
        position: fixed; /* 固定定位，覆盖整个窗口 */
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
        display: none; /* 默认隐藏 */
        justify-content: center; /* 水平居中 */
        align-items: center; /* 垂直居中 */
        z-index: 1000; /* 确保在最上层 */
        }

        /* 弹窗内容容器 */
        .modal-content {
        background: white;
        padding: 20px;
        border-radius: 8px;
        width: 300px; /* 宽度可自定义 */
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); /* 阴影效果 */
        text-align: center;
        }

        /* 关闭按钮样式 */
        .close-btn {
        margin-top: 15px;
        padding: 8px 16px;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        }

        .close-btn:hover {
        background: #0056b3;
        }
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
            .transition-custom {
                transition: all 0.3s ease;
            }
            
        }
        #store {
            align-items: center;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <header class="bg-gradient-to-r from-primary to-accent text-white shadow-lg">
        <div class="container mx-auto px-4 py-6">
            <h1 class="text-3xl font-bold flex items-center">
                <i class="fa fa-clock-o mr-3"></i>张宸煜的时间银行
            </h1>
            <p class="text-lg mt-1">&nbsp&nbsp存储每一刻，兑换每一分</p>
        </div>
    </header>

    <!-- 弹窗结构 -->
    <div class="modal-overlay" id="myModal">
        <div class="modal-content">
        <p>"爸爸非常抱歉的通知你，你可用时间不够多，请少取一些并努力积攒哦！🙂"</p>
        <button class="close-btn" onclick="hideModal()">确定</button>
        </div>
    </div>

    <main class="container mx-auto px-4 py-8">
        <!-- 未登录状态 -->
        <div id="unauthorized-view" class="max-w-md mx-auto">
            <div class="bg-white rounded-xl p-8 card-shadow">
                <h2 class="text-2xl font-bold text-center text-neutral mb-6">欢迎来到张宸煜的时间银行</h2>
                
                <div class="mb-6">
                    <button id="login-btn" class="w-full bg-primary hover:bg-primary/90 text-white font-semibold py-3 px-4 rounded-lg transition-custom flex items-center justify-center">
                        <i class="fa fa-sign-in mr-2"></i>登录
                    </button>
                </div>

            </div>
        </div>

        <!-- 登录表单 -->
        <form id="login-form" class="max-w-md mx-auto hidden">
            <div class="bg-white rounded-xl p-8 card-shadow">
                <h2 class="text-2xl font-bold text-center text-neutral mb-6">用户登录</h2>
                
                <div class="mb-4">
                    <label for="login-user-id" class="block text-gray-700 mb-2">用户ID</label>
                    <input type="text" id="login-user-id" value="张宸煜" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary" placeholder="请输入您的用户ID">
                </div>

                <div class="mb-4">
                    <label for="login-password" class="block text-gray-700 mb-2">密码</label>
                    <!-- 修复：密码输入框ID改为login-password，避免重复 -->
                    <input type="password" id="login-password" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary" placeholder="请输入您的密码">
                </div>
                
                <div class="mb-6">
                    <button id="do-login-btn" class="w-full bg-primary hover:bg-primary/90 text-white font-semibold py-3 px-4 rounded-lg transition-custom">
                        登录
                    </button>
                </div>
                
                <div class="text-center">
                    <button id="back-from-login-btn" type="button" class="text-gray-600 hover:text-primary transition-custom">
                        返回
                    </button>
                </div>
            </div>
        </form>

        <!-- 存入时间 -->
        <div id="authorized-view-store" class="hidden">
            <!-- 用户信息和可用时间块 -->
            <div class="bg-white rounded-xl p-6 mb-8 card-shadow max-w-md mx-auto mb-8">
                <div class="flex flex-col md:flex-row justify-between items-center">
                    <div class="text-center">
                        <h2 class="text-2xl font-bold text-neutral" id="user-name">用户名</h2>
                        <p class="text-gray-600" id="user-id-store">用户ID: xxxxxxxx</p>
                    </div>
                    <div class="mt-4 md:mt-0 bg-primary/10 px-6 py-4 rounded-lg text-center">
                        <p class="text-gray-600">可用时间</p>
                        <p class="text-3xl font-bold text-primary" id="available-time-store">0</p>
                        <p class="text-gray-600">分钟</p>
                    </div>
                </div>
            </div>

            <!-- 存入时间块 -->
            <form id="store-time" class="max-w-md mx-auto mb-8">
                <div class="bg-white rounded-xl p-6 card-shadow">
                    <h3 class="text-xl font-bold text-neutral mb-4 flex items-center">
                        <i class="fa fa-plus-circle text-secondary mr-2"></i>存入时间
                    </h3>
                    <div class="mb-4">
                        <label for="deposit-minutes" class="block text-gray-700 mb-2">分钟数</label>
                        <input type="number" id="deposit-minutes" min="1" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary" placeholder="请输入要存入的分钟数">
                    </div>
                    <button id="deposit-btn" class="w-full bg-secondary hover:bg-secondary/90 text-white font-semibold py-3 px-4 rounded-lg transition-custom">
                        确认存入
                    </button>
                </div>
            </form>

            <div class="mt-8 text-center">
                <button id="logout-btn-store" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-6 rounded-lg transition-custom">
                    <i class="fa fa-sign-out mr-1"></i>退出登录
                </button>
            </div>
        </div>

        <!-- 取出时间 -->
        <div id="authorized-view-get" class="hidden">
            <!-- 用户信息和可用时间块 -->
            <div class="bg-white rounded-xl p-6 mb-8 card-shadow max-w-md mx-auto mb-8">
                <div class="flex flex-col md:flex-row justify-between items-center">
                    <div>
                        <h2 class="text-2xl font-bold text-neutral" id="user-name">用户名</h2>
                        <p class="text-gray-600" id="user-id-get">用户ID: xxxxxxxx</p>
                    </div>
                    <div class="mt-4 md:mt-0 bg-primary/10 px-6 py-4 rounded-lg text-center">
                        <p class="text-gray-600">可用时间</p>
                        <p class="text-3xl font-bold text-primary" id="available-time-get">0</p>
                        <p class="text-gray-600">分钟</p>
                    </div>
                </div>
            </div>

            <!-- 取出时间块 -->
            <form id="get-time" class="max-w-md mx-auto mb-8">
                <div class="bg-white rounded-xl p-6 card-shadow">
                    <h3 class="text-xl font-bold text-neutral mb-4 flex items-center">
                        <i class="fa fa-minus-circle text-red-500 mr-2"></i>取出时间
                    </h3>
                    <div class="mb-4">
                        <label for="withdraw-minutes" class="block text-gray-700 mb-2">分钟数</label>
                        <input type="number" id="withdraw-minutes" min="1" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500" placeholder="请输入要取出的分钟数">
                    </div>
                    <button id="withdraw-btn" class="w-full bg-red-500 hover:bg-red-600 text-white font-semibold py-3 px-4 rounded-lg transition-custom">
                        确认取出
                    </button>
                </div>
            </form>

            <div class="mt-8 text-center">
                <button id="logout-btn-get" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-6 rounded-lg transition-custom">
                    <i class="fa fa-sign-out mr-1"></i>退出登录
                </button>
            </div>
        </div>
    </main>

    <!-- 消息提示框 -->
    <div id="message-box" class="fixed bottom-6 right-6 px-6 py-4 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center">
        <i id="message-icon" class="mr-3 text-xl"></i>
        <span id="message-text"></span>
    </div>

    <footer class="bg-neutral text-white mt-12 py-6">
        <div class="container mx-auto px-4 text-center">
            <p>&copy; 时间银行 - 珍惜每一刻</p>
        </div>
    </footer>

    <script>
        // 后端API地址，根据实际情况修改
        const API_BASE_URL = "http://122.51.236.176:8080";
        let currentUserId = null;

        // DOM元素
        const unauthorizedView = document.getElementById('unauthorized-view');
        const authorizedViewstore = document.getElementById('authorized-view-store');
        const authorizedViewget = document.getElementById('authorized-view-get');
        const loginForm = document.getElementById('login-form');

        // 获取弹窗元素
        const modal = document.getElementById('myModal');

        // 显示弹窗
        function showModal() {
            modal.style.display = 'flex'; // 启用 flex 布局，居中弹窗
        }

        // 隐藏弹窗
        function hideModal() {
        modal.style.display = 'none'; // 隐藏弹窗
        }
        
        // 消息提示函数
        function showMessage(text, isSuccess = true) {
            const messageBox = document.getElementById('message-box');
            const messageText = document.getElementById('message-text');
            const messageIcon = document.getElementById('message-icon');
            
            messageText.textContent = text;
            messageIcon.className = isSuccess ? 'fa fa-check-circle mr-3 text-xl text-green-500' : 'fa fa-exclamation-circle mr-3 text-xl text-red-500';
            messageBox.className = `fixed bottom-6 right-6 px-6 py-4 rounded-lg shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 flex items-center ${isSuccess ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`;
            
            setTimeout(() => {
                messageBox.className = 'fixed bottom-6 right-6 px-6 py-4 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center';
            }, 3000);
        }

        // 登录相关事件
        document.getElementById('login-btn').addEventListener('click', () => {
            let label = document.getElementById("login-user-id");
            label.value = "张宸煜"
            unauthorizedView.classList.add('hidden');
            loginForm.classList.remove('hidden');
        });

        document.getElementById('back-from-login-btn').addEventListener('click', () => {
            loginForm.classList.add('hidden');
            unauthorizedView.classList.remove('hidden');
        });

        document.getElementById('login-form').addEventListener('submit', async (e) => {
            // 修复：获取用户ID输入框（密码框ID已修改，不影响）
            const userId = document.getElementById('login-user-id').value.trim();
            // 修复：获取密码（如果需要验证密码，这里可以添加逻辑）
            const password = document.getElementById('login-password').value.trim();

            e.preventDefault();
            
            if (!userId) {
                showMessage('请输入用户ID', false);
                return;
            }
            
            try {
                // 修复：对用户ID进行URL编码，支持中文等特殊字符
                const encodedUserId = encodeURIComponent(userId);
                const response = await fetch(`${API_BASE_URL}/user?user_id=${userId}&pwd=${password}`);
                
                if (!response.ok) {
                    throw new Error('用户不存在');
                }
                
                const user = await response.json();

                currentUserId = userId;
                if (user.active == 'N') {
                    showMessage("用户名或密码不正确，请重新输入!", false)
                    return
                }

                document.getElementById('user-id-store').textContent = `用户ID: ${userId}`;
                document.getElementById('user-id-get').textContent = `用户ID: ${userId}`;
                document.getElementById('available-time-store').textContent = user.available_time || 0;
                document.getElementById('available-time-get').textContent = user.available_time || 0;
                // 清空表单
                document.getElementById('login-user-id').value = '';
                document.getElementById('login-password').value = '';
                if (user.admin == 'Y') {
                    // 切换视图
                    loginForm.classList.add('hidden');
                    authorizedViewstore.classList.remove('hidden');
                    // 加载交易历史
                    // loadTransactionHistory();
                } else {
                    // 切换视图
                    loginForm.classList.add('hidden');
                    authorizedViewget.classList.remove('hidden');
                }
                
                
                showMessage('登录成功');
            } catch (error) {
                showMessage(error.message, false);
            }
        });

        // 退出登录
        document.getElementById('logout-btn-store').addEventListener('click', () => {
            currentUserId = null;
            authorizedViewstore.classList.add('hidden');
            unauthorizedView.classList.remove('hidden');
            showMessage('已退出登录');
        });
        document.getElementById('logout-btn-get').addEventListener('click', () => {
            currentUserId = null;
            authorizedViewget.classList.add('hidden');
            unauthorizedView.classList.remove('hidden');
            showMessage('已退出登录');
        });

        // 存入时间
        document.getElementById('store-time').addEventListener('submit', async (e) => {
            if (!currentUserId) return;
            
            e.preventDefault();
            const minutes = parseInt(document.getElementById('deposit-minutes').value);
            
            if (!minutes || minutes <= 0) {
                showMessage('请输入有效的分钟数', false);
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/deposit`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        minutes
                    })
                });
                
                if (!response.ok) {
                    throw new Error('存入失败');
                }
                
                const data = await response.json();
                document.getElementById('available-time-store').textContent = data.available_time;
                
                // 清空表单
                document.getElementById('deposit-minutes').value = '';
                            
                showMessage(`成功存入 ${minutes} 分钟`);
            } catch (error) {
                showMessage(error.message, false);
            }
        });


        // 取出时间
        document.getElementById('get-time').addEventListener('submit', async (e) => {
            if (!currentUserId) return;
            e.preventDefault();
            
            const minutes = parseInt(document.getElementById('withdraw-minutes').value);
            const str = document.getElementById("available-time-get").textContent;
            // 使用正则表达式匹配数字（\d+ 表示匹配1个或多个数字）
            const match = str.match(/\d+/);
            let remain_time = 0;
            // 提取结果（如果匹配成功）
            if (match) {
                const x = match[0]; // 获取匹配到的数字字符串
                remain_time = parseInt(x, 10); // 转换为整数
            }
            if(remain_time < minutes) {
                // alert("非常抱歉的通知你，你已无可用时间，请努力积攒！🙂");
                showModal();
                return;
            }
            
            if (!minutes || minutes <= 0) {
                showMessage('请输入有效的分钟数', false);
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/withdraw`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        minutes
                    })
                });
                
                if (!response.ok) {
                    const data = await response.json();
                    throw new Error(data.message || '取出失败');
                }
                
            

                const data = await response.json();
                document.getElementById('available-time-get').textContent = data.available_time || 0;
                
                // 清空表单
                document.getElementById('withdraw-minutes').value = '';
                
                showMessage(`成功取出 ${minutes} 分钟`);
            } catch (error) {
                showMessage(error.message, false);
            }
        });

        
        // 格式化日期时间
        function formatDateTime(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    </script>
</body>
</html>